<template>
	<div>
		<div class="search-box">
            <el-select class="mr10" v-model="query.project_id" multiple filterable placeholder="项目编号">
                <el-option
                    v-for="project_id in projectList"
                    :key="project_id"
                    :label="project_id"
                    :value="project_id">
                </el-option> 
            </el-select>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
			<template v-if="props.Edit==='samMan'">
				<el-button type="warning" :icon="WarningFilled" @click="handleArrayCheck">批量审核</el-button>
			</template>
			<template v-if="props.Edit==='samIns'">
				<el-button type="success" :icon="InfoFilled" @click="handleArrayInstock">批量入库</el-button>
				<el-button type="danger" :icon="RemoveFilled" @click="handleArrayOver">样品检毕</el-button>
			</template>
			<template v-if="props.Edit==='samRec'">
				<el-button type="success" :icon="WarningFilled" @click="handleArrayOver">审核通过</el-button>
				<el-button type="warning" :icon="WarningFilled" @click="handleArrayOver">审核退回</el-button>
			</template>
			<template v-if="props.Edit==='samRem'">
				<el-button type="warning" :icon="RemoveFilled" @click="handleArrayRemove">批量清退</el-button>
			</template>
			<slot name="s1"></slot>
		</div>
		<el-table ref="multipleTable" :data="tableSplit()" border header-cell-class-name="table-header"
			@selection-change="handleSelection">
			<el-table-column prop="id" label="ID" width="55" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="project_id" label="项目编号" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="sample_id" label="样品编号" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="sample_name" label="样品名称" align="center" show-overflow-tooltip></el-table-column>
			<template v-if="props.Edit==='samMan'">
				<el-table-column prop="client_id" label="客户编号" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="lot_number" label="批号" align="center" show-overflow-tooltip></el-table-column>
			</template>
			<el-table-column prop="sample_amount" label="原始数量" align="center" show-overflow-tooltip></el-table-column>
			<el-table-column prop="size" label="原始规格" align="center" show-overflow-tooltip></el-table-column>
			<template v-if="props.Edit==='samRec'||props.Edit==='samRem'||props.Edit==='samIns'">
				<el-table-column prop="current_amount" label="原始库存量" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="disp_amount" label="分装总库存" align="center" show-overflow-tooltip></el-table-column>
				<el-table-column prop="disp_size" label="分装规格" align="center" show-overflow-tooltip></el-table-column>
			</template>
			<!-- <el-table-column prop="arrive_time" label="到样日期" align="center" show-overflow-tooltip></el-table-column> -->
			<el-table-column prop="instock_time" label="入库日期" align="center" show-overflow-tooltip></el-table-column>
			<!-- <el-table-column prop="create_time" label="有效日期" align="center" show-overflow-tooltip></el-table-column> -->
			<el-table-column prop="status" label="样品状态" align="center" show-overflow-tooltip>
				<template #default="scope">
					<el-tag v-if="scope.row.status===0" type="info">未审核</el-tag>
					<el-tag v-if="scope.row.status===1" type="warning">暂存</el-tag>
					<el-tag v-if="scope.row.status===2" type="primary">待检</el-tag>
					<el-tag v-if="scope.row.status===3" type="success">在检</el-tag>
					<el-tag v-if="scope.row.status===4" type="danger">检毕</el-tag>
					<el-tag v-if="scope.row.status===5" type="danger">销毁</el-tag>
					<el-tag v-if="scope.row.status===6" type="warning">返回</el-tag>
				</template>
			</el-table-column>
			<template v-if="props.Edit==='samMan'">
				<el-table-column label="操作" align="center" width="280px">
					<template #default="scope">
						<el-button
							type="primary"
							size="small"
							:icon="View"
							@click="handleView(scope.row)"
							v-permiss="15"
						>
							查看
						</el-button>
						<el-button
							type="success"
							size="small"
							:icon="Edit"
							@click="handleEdit(scope.$index,scope.row,'样品审核|编辑')"
							v-permiss="15"
						>
							编辑
						</el-button>
						<el-button
							type="danger"
							size="small"
							:icon="Delete"
							@click="recordDelete(scope.$index,scope.row,'样品审核|删除')"
							v-permiss="15"
						>
							删除
						</el-button>
					</template>
        		</el-table-column>
			</template>
			<template v-if="props.Edit==='samIns'">
				<el-table-column label="操作" align="center" width="120px">
					<template #default="scope">
						<el-button
							type="primary"
							size="small"
							:icon="View"
							@click="handleView(scope.row)"
							v-permiss="15"
						>
							查看
						</el-button>
					</template>
        		</el-table-column>
			</template>
			<!-- <template v-if="props.Edit==='samRec'">
				<el-table-column label="操作" align="center" width="180px">
					<template #default="scope">
						<el-button
							type="primary"
							size="small"
							:icon="View"
							@click="handleView(scope.row)"
							v-permiss="15"
						>
							查看
						</el-button>
						<el-button
							type="success"
							size="small"
							:icon="Edit"
							@click="handleView(scope.row)"
							v-permiss="15"
						>
							编辑
						</el-button>
					</template>
        		</el-table-column>
			</template> -->
			<template v-if="props.Edit==='samRem'">
				<el-table-column label="操作" align="center" width="280px">
					<template #default="scope">
						<el-button
							type="primary"
							size="small"
							:icon="View"
							@click="handleView(scope.row)"
							v-permiss="15"
						>
							查看
						</el-button>
						<el-button
							type="success"
							size="small"
							:icon="Edit"
							@click="handleEdit(scope.$index,scope.row,'样品清退|编辑')"
							v-permiss="15"
						>
							编辑
						</el-button>
						<el-button
							type="warning"
							size="small"
							:icon="RemoveFilled"
							@click="recordDelete(scope.$index,scope.row,'样品清退|删除')"
							v-permiss="15"
						>
							清退
						</el-button>
					</template>
        		</el-table-column>
			</template>
			<el-table-column type="selection"></el-table-column>
		</el-table>
		<div class="pagination">
			<el-pagination
				background
				layout=" prev, pager, next,jumper,total"
				:current-page="state.pageIndex"
				:page-size="state.pageSize"
				:total="pageTotal"
				@current-change="handlePageChange"
			></el-pagination>
		</div>
		<el-dialog 
			draggable 
			title="样品详情" 
			v-model="viewVisible" 
			destroy-on-close
			:close-on-click-modal="false"
		>
			<sampleDetail :data="rowData" :Type="Type" />
		</el-dialog>
		<el-dialog 
			title="样品编辑" 
			v-model="editVisible" 
			destroy-on-close
			:close-on-click-modal="false"
		>
			<sampleEdit :data="rowData" :edit="idEdit" :actionType="actionType" :update="update" />
		</el-dialog>
		<el-dialog 
			draggable 
			title="操作记录" 
			v-model="reasonVisible"
			width="800px" 
			destroy-on-close
			:close-on-click-modal="false"
		>
			<recordEdit :data="rowData" :actionType="actionType" :conFirm="handleDelete" ref="OptRecord"></recordEdit>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { pa } from 'element-plus/es/locale'
import { ref,reactive, onMounted,onActivated, onServerPrefetch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import recordEdit from '../../record/recordEdit.vue'
import sampleDetail from './sample_detail.vue'
import sampleEdit from './sample_edit.vue'
import { Delete, InfoFilled, WarningFilled,Search,Edit, Sort, CirclePlusFilled, View,RemoveFilled } from '@element-plus/icons-vue'
import useSample from '../../../hooks/Sample/useSample'
import useUtils from '../../../hooks/useUtils'

const { getSample,postSample,delSample,querySample,postSampleAction,sam_url } = useSample()
/* 接收父组件值 */
const props = defineProps({
	tableData: {
		type:Object,
		required: false
	},
	Edit: {
		type: String,
		required: false
	}
})
interface TableItem { 
	id: number;
	project_id: string;
	client_id: string;
	sample_id: string;
	sample_name: string;
	lot_number: string;
	size: string;
	sample_amount: number;
	current_amount: number;
	disp_amount: number;
	disp_size: string;
	arrive_time: string;
	instock_time: string;
	create_time: string;
	status:number;
}
/* 数据表格初始化 */
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
const projectList = ref([])
const { arrRemoveDup } = useUtils()
const reload = () => {
	getSample().then(res=>{
		tableData.value = res.data["samples"];
		pageTotal.value = res.data["pageTotal"];
		for(let item of tableData.value){
			projectList.value.push(item.project_id)
		}
		projectList.value=arrRemoveDup(projectList.value)
	})
}
/* 刷新方法 */
defineExpose({
	reload,
})

const state = reactive({
	page:1,
	limit:20,
	pageIndex:1,
	pageSize:20,
	total:pageTotal
})

const tableSplit = () => {
	if(props.Edit==="samMan"){
		const table = ref(tableData.value.filter(
			(item,index) => {
				return item.status === 0
			}
		))
		pageTotal.value = table.value.length
		return(table.value.filter(
			(item,index) => {
				return index < state.page * state.limit && index >= state.limit*(state.page - 1)
			}
		))
	}
	if(props.Edit==="samIns"){
		const table = ref(tableData.value.filter(
			(item,index) => {
				return item.status === 1 || item.status === 2
			}
		))
		pageTotal.value = table.value.length
		return(table.value.filter(
			(item,index) => {
				return index < state.page * state.limit && index >= state.limit*(state.page - 1) 
			}
		))
	}
	if(props.Edit==="samRec"){
		const table = ref(tableData.value.filter(
			(item,index) => {
				return item.status === 3
			}
		))
		pageTotal.value = table.value.length
		return(table.value.filter(
			(item,index) => {
				return index < state.page * state.limit && index >= state.limit*(state.page - 1) 
			}
		))
	}
	if(props.Edit==="samRem"){
		return(tableData.value.filter(
			(item,index) => {
				return index < state.page * state.limit && index >= state.limit*(state.page - 1)
			}
		))
	}
}

const handlePageChange = (val: number) => {
	state.pageIndex = val;
	state.page = val;
};
/* 记录多选选项 */
let multiple_selection = reactive([])
const handleSelection = (val:any) => {
	if(val.length === 0){
	} else {
		multiple_selection = val
	}
}
const actionType = ref("")	
/* 样品基础信息： 批量审核 */
const handleArrayCheck = () => {
	if (multiple_selection.length === 0 ){
		ElMessage.error("请选择至少一个样品！！")
	}else{
		ElMessageBox.confirm('确定审核吗？', '提示',{
			type:"warning",
			draggable: true,
		})
		.then( res => {
			for( let item of multiple_selection ){
				postSampleAction(item,"check")
				for(var idx=0;idx<tableData.value.length;idx++){
					if(tableData.value[idx].id===item.id){
						console.log(tableData.value[idx].current_amount)
						tableData.value[idx].status=1
					}
            	}
			}
			ElMessage.success('审核成功！');
		}).catch(() => {});
	}
}
/* 样品出入库：批量入库 */
const handleArrayInstock = () => {
	if (multiple_selection.length === 0 ){
		ElMessage.error("请选择至少一个样品！！")
	}else{
		ElMessageBox.confirm('确定入库吗？', '提示',{
			type:"success",
			draggable: true,
		})
		.then( res => {
			for( let item of multiple_selection ){
				postSampleAction(item,"instock")
				for(var idx=0;idx<tableData.value.length;idx++){
					if(tableData.value[idx].id===item.id){
						tableData.value[idx].current_amount=tableData.value[idx].sample_amount
						tableData.value[idx].status=2
					}
            	}
			}
			ElMessage.success('入库成功！');
		}).catch(() => {});
	}
}
/* 样品出入库：批量检毕 */
const handleArrayOver = () => {
	if (multiple_selection.length === 0 ){
		ElMessage.error("请选择至少一个样品！！")
	}else{
		ElMessageBox.confirm('确定检毕吗？', '提示',{
			type:"warning",
			draggable: true,
		})
		.then( res => {
			for( let item of multiple_selection ){
				postSampleAction(item,"over")
				for(var idx=0;idx<tableData.value.length;idx++){
					if(tableData.value[idx].id===item.id){
						tableData.value[idx].status=4
					}
            	}
			}
			ElMessage.error('样品检毕！');
		}).catch(() => {});
	}
}
/*样品清退：批量清退 */
const handleArrayRemove = () => {
	if (multiple_selection.length === 0 ){
		ElMessage.error("请选择至少一个样品！！")
	}else{
		ElMessageBox.confirm('确定清退吗？', '提示',{
			type:"warning",
			draggable: true,
		})
		.then( res => {
			for( let item of multiple_selection ){
				delSample(item["id"])
				for( const [key,value] of Object.entries(tableData.value)){
					if(value["id"] === item["id"]){
						tableData.value.splice(parseInt(key),1)
					}	
				}
				
			}
			ElMessage.warning('清退成功！');
		}).catch(() => {});
	}
}
/* 设置查看参数 */
const viewVisible = ref(false)
const rowData = ref({})
const Type = ref("")
/* 查看样品信息 */
const handleView = (row: TableItem) => {
	viewVisible.value=true;
	rowData.value=row;
	Type.value="samMan";
}
/* 编辑信息 */
const index=ref(-1)
const editVisible = ref(false)
const idEdit = ref(false)
const handleEdit = (idx:number,row:TableItem,tag:string) => {
	editVisible.value=true;
	idEdit.value=true;
	index.value=idx;
	rowData.value=row;
	actionType.value=tag;
}
/* 编辑方法 */
const editUpdate = (row:TableItem) => {
	editVisible.value=false
}

/* 项目检索 */
const query = reactive({
	project_id: "",
	limit: 2,
	pageIndex: 1,
	pageSize: 1
});
/* 检索方法 */
const handleSearch = () => {
	if(query.project_id.length === 0){
		ElMessage({
			type: 'error',
			message: `请选中至少一个项目！`,
		})
	}else{
		querySample(query).then( res => {
			tableData.value=res.data
		})
	}
}
/* 列表删除 */
const recordDelete = (idx:number,row:TableItem,tag:string) => {
	index.value = idx;
	rowData.value = row;
	actionType.value = tag;
	record();
}

const OptRecord = ref()
const handleDelete = (row:any) => {
	ElMessageBox.confirm('确定要删除/清退吗？', '提示', {
		type: 'warning',
		draggable: true,
	})
	.then(() => {
		delSample(row.data.id).then( res => {
			if(res.data === 202){
				tableData.value.splice(index.value, 1);
				OptRecord.value.postRecord(row).then(res=>{
					if(res.data===202){
						ElMessage.success("行为成功记录！")
					}else{
						ElMessage.error("行为记录出错！")
					}
				})
				reasonVisible.value=false;
				ElMessage.warning('删除/清退成功！');
			}else if(res.status === 404){
				ElMessage.error('删除/清退出错！');
			}
		});
	
	})
	.catch(() => {});
}
/* 样品基础信息： 批量删除 */
const handleArraydelete = () => {
	ElMessageBox.confirm('确定要删除/清退吗？', '提示', {
		type: 'warning',
		draggable: true,
	})
	.then( () => {
		if (multiple_selection.length === 0 ){
			ElMessage.error("请选中至少一个样品！！")
		}else{
			for( let item of multiple_selection){
				
			}
			ElMessage.success('删除/清退成功');
		}
	})
	.catch(() => {});
}
/* 操作记录 */
const reasonVisible=ref(false)
const record = () => {
	reasonVisible.value=true
}
const update = () => {
	editVisible.value=false
	reload()
}

</script>

<style scoped>

.search-box {
	margin-bottom: 20px;
	float:left
}

.mr10 {
	margin-right: 10px;
} 
.el-select {
	width: 800px;
}

.search {
	float:right;
	margin-bottom: 20px;
}

.search-input {
	width: 200px;
}


.el-link {
  margin-left: 8px;
}

.mr10 {
	margin-right: 10px;
}

.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}

.content-title {
    font-weight: 400;
    line-height: 50px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}
.upload-demo {
    width: 360px;
}
</style>
